package com.dmall.chapter03.section02;

import java.util.Arrays;

/**
 * 不使用额外的数组，使用交换元素的方式
 * 时间复杂度：O(n)
 * 空间复杂度：O(1)
 * @author xiao1.wang
 * @date 2020-12-01 10:10:03
 */
public class Leetcode283V3 {

    public void moveZeroes(int[] nums) {
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                swap(nums, i, index++);
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void main(String[] args) {
        Leetcode283V3 leetcode283 = new Leetcode283V3();
        int[] nums = {0, 1, 0, 3, 12};
        leetcode283.moveZeroes(nums);
        Arrays.stream(nums).forEach(System.out::println);
    }
}
